package com.example.drive.net.request

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

/**
 * POST提交文件
 */
class FileRequest constructor(
    url: String,
    tag: Any = Any(),
    private val params: Map<String, String> = mapOf(),
    private val file: File
) : OkHttpRequest(url, tag) {
    private val requestBody by lazy {
        val contentType = "application/octet-stream".toMediaTypeOrNull()
        file.asRequestBody(contentType)
    }

    override fun createRequest(): Request {
        val body = MultipartBody.Builder().setType(MultipartBody.FORM).run {
            params.forEach {
                addFormDataPart(it.key, it.value)
            }
            addFormDataPart("File", file.name, requestBody).build()
        }
        return builder.post(body).build()
    }
}